<?php

namespace app\service;

use app\common\BaseService;
use app\model\House as HouseModel;
use app\model\HouseInOrder;
use app\service\GoodsService;
use think\facade\Db;

class HouseService extends BaseService
{
  public static function getInstance(): HouseService
  {
    return parent::getInstance();
  }

  public static function getModel(): HouseModel
  {
    return HouseModel::getInstance();
  }

  /*
   * 根据ID获取商品表
   */
  public static function getGoodsById($id) {
    return self::getModel()
      ->where('id', '=', $id)
      ->find()
      ->toArray();
  }

  /*
   * 连商品表goods查询house信息
   */
  public static function getHouseJoinGoods($conditions = []) {
    $conditions[] = ['h.status', 1,'='];
    $query = Db::name('house')
      ->alias('h')
      ->field('h.*,g.category_id,g.name,g.unit,g.sellable,g.price as sell_price,g.sale_name, g.conversion')
      ->join('goods g', 'g.id = h.goods_id', 'LEFT');
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $query = $query->where($field, $op, $value);
    }
    $query = $query->order('h.id', 'DESC');
    return $query->select()->toArray();
  }

  /*
   * 实时仓库新增
   */
  public static function createHouse($process, $data) {
    $goods = GoodsService::getGoodsById($data['goods_id']);
    // 获取house表数据
    $house = self::getHouseJoinGoods([['h.goods_id', $data['goods_id'], '='], ['h.process', $process, '=']]);
    $house = isset($house[0]) ? $house[0] : [];
    // 更新到house
    $updateHouse = [];
    // 新增到house
    $insertHouse = [];
    // 新增到house_in
    $insertHouseIn = [];
    // 入库的数量
    $count = $data['count_in'] * $goods['conversion'];
    // 入库总价
    $totalAmount = $data['count_in'] * $data['price_in'];
    if ($house) {
      // 更新到house
      $updateHouse = [
        'count' => $house['count'] + $count,
        'total_amount' => round($house['total_amount'] + $totalAmount, 2),
        'price' => round(($house['total_amount'] + $totalAmount) / ($house['count'] + $count), 2),
        'last_update_time' => date('Y-m-d')
      ];
    } else {
      // 新增到house
      $insertHouse = [
        'goods_id' => $goods['id'],
        'count' => $count,
        'total_amount' => round($totalAmount, 2),
        'price' => round($totalAmount / $count, 2),
        'process' => $process,
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    // 获取house_in
    $houseIn = HouseInService::getInstance()->getHouseInByCondition([['insert_time', date('Y-m-d'), '>=']]);
    $arr = array_column($houseIn, 'house_in_number');
    $num = str_pad(count($arr) + 1, 4, '0',STR_PAD_LEFT);
    $houseInNumber = 'CG'.date('Ymd').$num;
    // 新增到house_in
    $insertHouseIn = [
      'goods_id' => $goods['id'],
      'house_in_number' => $houseInNumber,
      'price_in' => $data['price_in'],
      'count_in' => $data['count_in'],
      'count' => $count,
      'total_amount' => round($totalAmount, 2),
      'price' => round($totalAmount / $count, 2),
      'supplier' => isset($data['supplier']) ? $data['supplier'] : '',
      'comment' => isset($data['comment']) ? $data['comment'] : '',
      'process' => $process,
      'status' => 1,
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];

    self::getModel()->startTrans();
    try {
      // 新增house
      if ($insertHouse) {
        $res1 = self::getModel()->save($insertHouse);
        if ($res1 === false) {
          throw new \Exception('新增house失败');
        }
      }
      // 更新house
      if ($updateHouse) {
        $res2 = self::getModel()
          ->where('id','=', $house['id'])
          ->save($updateHouse);
        if ($res2 === false) {
          throw new \Exception('更新house失败');
        }
      }
      // 新增house_in
      if ($insertHouseIn) {
        $res3 = HouseInService::getModel()->save($insertHouseIn);
        if ($res3 === false) {
          throw new \Exception('新增house_in失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 原料批量新增
   */
  public static function createMultiHouse($data) {
    $process = $data['process'];
    $supplier = $data['supplier'];
    $defaultTime = $data['default_time'];
    $data = $data['data'];
    // 获取商品表数据
    $goodsList = GoodsService::getInstance()->getGoodsByCondition([['process', $process, '='], ['status', 1, '=']]);
    $goodsList = array_column($goodsList, null, 'id');
    // 获取house_in
    $houseIn = HouseInService::getInstance()->getHouseInByCondition([['insert_time', date('Y-m-d'), '>='], ['process', 0, '=']]);
    $arr = array_column($houseIn, 'house_in_number');
    $num = str_pad(count($arr) + 1, 4, '0',STR_PAD_LEFT);
    $houseInNumber = 'CG'.date('Ymd').$num;
    // 新增到house_in_order
    $insertInOrder = [
      'house_in_number' => $houseInNumber,
      'supplier' => $supplier,
      'process' => $process,
      'default_time' => $defaultTime,
      'status' => 2,
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    // 新增到house_in
    $insertHouseIn = [];
    foreach ($data as $value) {
      $goodsId = $value['goods_id'];
      $conversion = isset($value['conversion']) ? $value['conversion'] : $goodsList[$goodsId]['conversion'];
      // 入库的数量
      $count = $value['count_in'] * $conversion;
      // 入库总价
      $totalAmount = $value['count_in'] * $value['price_in'];
      $insertHouseIn[] = [
        'goods_id' => $goodsId,
        'in_order_id' => '',
        'price_in' => $value['price_in'],
        'count_in' => $value['count_in'],
        'conversion' => $value['conversion'],
        'count' => $count,
        'total_amount' => round($totalAmount, 2),
        'price' => round($totalAmount / $count, 2),
        'comment' => $value['comment'],
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    self::getModel()->startTrans();
    try {
      // 新增house_in_order
      if ($insertInOrder) {
        $res1 = HouseInService::getModel()
          ->insertGetId($insertInOrder);
        if ($res1 === false) {
          throw new \Exception('新增house_in_order失败');
        }
      }
      // 新增house_in
      if ($insertHouseIn) {
        foreach ($insertHouseIn as &$v) {
          $v['in_order_id'] = $res1;
        }
        $res2 = HouseInService::getDetailModel()->insertAll($insertHouseIn);
        if (!$res2) {
          throw new \Exception('新增house_in失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 售出仓库商品
   */
  public static function sellProduct($id, $data) {
    // 获取house表实时数据
    $house = self::getModel()
      ->where('id', '=', $id)
      ->find()
      ->toArray();
    // 获取商品详情
    $goods = GoodsService::getModel()
      ->find($house['goods_id'])
      ->toArray();
    // 查询门店已有库存
    $store = StoreService::getModel()
      ->where('name', '=', $goods['sale_name'])
      ->where('base', '=', $data['base'])
      ->find();
    if ($store) {
      $store = $store->toArray();
    } else {
      $store = [];
    }
    // 获取inner_purchase表数据
    $cond = [['insert_time', date('Y-m-d'), '>=']];
    $inner = InnerPurchaseService::getModel()->getDataByCondition($cond);
    $arr = array_column($inner, 'sell_number');
    $num = str_pad(count($arr) + 1, 3, '0',STR_PAD_LEFT);
    $sellNumber = 'DD'.date('Ymd').$num;
    if ($data['count'] > $house['count']) {
      return ['status' => false, 'msg' => '库存不足'];
    }
    // 修改house表数据
    $updateHouse = [
      'count' => $house['count'] - $data['count'],
      'total_amount' => round(($house['count'] - $data['count']) * $house['price'], 2),
      'last_update_time' => date('Y-m-d')
    ];
    // 新增house_out表数据
    $insertHouseOut = [
      'goods_id' => $house['goods_id'],
      'sell_number' => $sellNumber,
      'price' => $house['price'],
      'sell_price' => isset($data['sell_price']) ? $data['sell_price'] : 0,
      'count' => $data['count'],
      'base' => $data['base'],
      'comment' => $data['comment'],
      'type' => 2,
      'process' => $house['process'],
      'sale_time' => date('Y-m-d', strtotime($data['sale_time'])),
      'status' => 1,
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    // 新增inner_purchase_order表数据
    $insertInnerOrder = [
      'sell_number' => $sellNumber,
      'base' => $data['base'],
      'house_sell' => 1,
      'purchase_time'=> date('Y-m-d', strtotime($data['sale_time'])),
      'operate_time' => date('Y-m-d', strtotime($data['sale_time'])),
      'confirm_time' => date('Y-m-d', strtotime($data['sale_time'])),
      'comment' => $data['comment'],
      'status' => 1,
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    // 新增inner_purchase表数据
    $insertInner = [
      'inner_order_id' => '',
      'house_out_id' => '',
      'price' => isset($data['sell_price']) ? $data['sell_price'] : 0,
      'count' => $data['count'],
      'goods_id' => $house['goods_id'],
      'comment' => $data['comment'],
      'status' => 1,
      'insert_time' => date('Y-m-d H:i:s'),
      'last_update_time' => date('Y-m-d H:i:s')
    ];
    // 新增store_house数据
    $insertStore = [];
    // 修改store_house数据
    $updateStore = [];
    if ($store) {
      $totalAmount = $data['count'] * (isset($data['sell_price']) ? $data['sell_price'] : 0);
      $updateStore = [
        'count' => $store['count'] + $data['count'],
        'goods_id' => $house['goods_id'],
        'category_id' => $goods['category_id'],
        'total_amount' => round($store['total_amount'] + $totalAmount, 2),
        'price' => round(($store['total_amount'] + $totalAmount) / ($store['count'] + $data['count']), 2),
        'last_update_time' => date('Y-m-d')
      ];
    } else {
      $insertStore = [
        'goods_id' => $house['goods_id'],
        'category_id' => $goods['category_id'],
        'name' => $goods['sale_name'],
        'count' => $data['count'],
        'total_amount' => round($data['count'] * $data['sell_price'], 2),
        'price' => round($data['sell_price'], 2),
        'base' => $data['base'],
        'status' => 1,
        'insert_time' => date('Y-m-d H:i:s'),
        'last_update_time' => date('Y-m-d H:i:s')
      ];
    }
    self::getModel()->startTrans();
    try {
      // 更新house
      if ($updateHouse) {
        $res1 = self::getModel()
          ->where('id', '=', $id)
          ->save($updateHouse);
        if ($res1 === false) {
          throw new \Exception('更新house失败');
        }
      }
      // 新增house_out
      if ($insertHouseOut) {
        $res2 = HouseOutService::getModel()->insertGetId($insertHouseOut);
        if ($res2 === false) {
          throw new \Exception('新增house_out失败');
        }
      }
      // 新增inner_purchase_order
      if ($insertInnerOrder) {
        $res3 = InnerPurchaseService::getModel()->insertGetId($insertInnerOrder);
        if ($res3 === false) {
          throw new \Exception('新增inner_purchase_order失败');
        }
      }
      // 新增inner_purchase
      if ($insertInner) {
        if ($res2) {
          $insertInner['house_out_id'] = $res2;
        }
        if ($res3) {
          $insertInner['inner_order_id'] = $res3;
        }
        $res4= InnerPurchaseService::getDetailModel()->save($insertInner);
        if ($res4 === false) {
          throw new \Exception('新增inner_purchase失败');
        }
      }
      // 新增store_house
      if ($insertStore) {
        $res5 = StoreService::getModel()->save($insertStore);
        if ($res5 === false) {
          throw new \Exception('新增store_house失败');
        }
      }
      // 更新store_house
      if ($updateStore) {
        $res6 = StoreService::getModel()
          ->where('id', '=', $store['id'])
          ->save($updateStore);
        if ($res6 === false) {
          throw new \Exception('更新store_house失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /**
   * 获取仓库实时库存
   */
  public static function getHouseCount($nums, $oid = '') {
    $rest = [];
    // 获取仓库信息
    if ($nums) {
      $list = self::getHouseJoinGoods([['g.id', $nums, 'IN']]);
      $houseCount = array_column($list, 'count', 'goods_id');
      // 获取申请表中的数据
      $condition = [
        ['o.status', [2,3], 'IN'],
        ['i.status', 1, '='],
        ['i.goods_id', $nums, 'IN']
      ];
      if ($oid) {
        $condition[] = ['o.id', $oid, 'NOT IN'];
      }
      $innerCount = [];
      // 获取申请表中的该商品的数量
      $inner = InnerPurchaseService::getInstance()->getInnerJoinGoods($condition);
      foreach ($inner as $value) {
        if(isset($innerCount[$value['goods_id']])) {
          $innerCount[$value['goods_id']] += $value['count'];
        } else {
          $innerCount[$value['goods_id']] = $value['count'];
        }
      }
    }
    foreach ($nums as $num) {
      if (isset($houseCount[$num]) && $houseCount[$num]) {
        $count = isset($innerCount[$num]) ? $innerCount[$num] : 0;
        $rest[$num] = $houseCount[$num] - $count;
      } else {
        $rest[$num] = 0;
      }
    }
    return $rest;
  }
}